package com.hc.core.web.springmvc;

import java.io.File;
import java.io.OutputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import org.springframework.web.servlet.ModelAndView;

import com.hc.core.AppException;
import com.hc.core.util.DateTool;
import com.hc.core.util.GenericsUtils;
import com.hc.core.util.StringUtil;
import com.hc.core.web.WebConfig;
import com.hc.core.web.WebException;

/**
 * 基本的增删改查前端处理类。<br>
 * 实现了对指定对象基本的增删改查方法。<br>
 * 另外，增加了处理数据绑定和数据校验的两个便利方法。<br>
 * 
 */

public class BaseCURDController<V> extends BaseController {

	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger
			.getLogger(BaseCURDController.class);

	/**
	 * 删除服务器文件
	 */
	public void deleteFile(String filePath) {
		File file = new File(filePath);
		if (file.exists()) {
			file.delete();
		}
	}

	/**
	 * 初始化错误信息
	 * 
	 * @param mnv
	 * @param object
	 * @param message
	 */
	public void initExceptionMessage(ModelAndView mnv, Object object,
			String message) {
		mnv.addObject(WebConfig.DATA_NAME, object);
		mnv.addObject(WebConfig.MESSAGE_NAME, message);
	}

	/**
	 * 导出Excel
	 * 
	 * @param response
	 */
	public void export(HttpServletResponse response, String tableName,
			String[] dataHeader, List dataList) {
		String fileName = tableName + "_" + DateTool.getDate();
		
		// 创建模板
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet(fileName);
		sheet.setDefaultColumnWidth((short) 16);
		sheet.setAutobreaks(true);

		HSSFCellStyle titleStyle = getTitleStyle(wb);
		HSSFCellStyle columnHeaderStyle = getColumnHeaderStyle(wb);
		
		int lineNum = 0;
		// 1.设置报表标题
		HSSFCell titleCell = sheet.createRow(lineNum).createCell(
				(short) (dataHeader.length / 2));
		titleCell.setCellValue(tableName);
		titleCell.setCellStyle(titleStyle);
		
		lineNum = 1;
		// 2.设置表头
		HSSFRow headRow = sheet.createRow(lineNum);
		for (int i = 0; i < dataHeader.length; i++) {
			HSSFCell cell = headRow.createCell(i);
			cell.setCellValue(StringUtil.filterNull(dataHeader[i]));
			cell.setCellStyle(columnHeaderStyle);
		}
		
		lineNum = 2;
		// 3.设置表身
		String cellValue = "";
		for (int i = 0; null != dataList && i < dataList.size(); i++) {
			HSSFRow bodyRow = sheet.createRow(lineNum + i);
			HashMap map = (HashMap)dataList.get(i);
			Collection c = map.values();
			Iterator it = c.iterator();
	        for (int j=0; it.hasNext(); j++) {
	        	HSSFCell cell = bodyRow.createCell(j);
	        	cellValue = String.valueOf(it.next());
	        	if(null != cellValue && cellValue.length() > 0){
	        		cell.setCellValue(cellValue);
	        	}
	        }
		}

		try {
			response.setHeader("Content-Disposition", "attachment;filename="
					+ new String(fileName.getBytes("UTF-8"), "ISO8859-1")
					+ ".xls");
			response.setContentType("application/vnd.ms-excel");
			OutputStream out = response.getOutputStream();
			wb.write(out);
			out.flush();
		} catch (Exception e) {
			logger.error("导出excel文件时出现异常", e);
		}
	}

	/**
	 * 设置报表标题的样式
	 */
	protected HSSFCellStyle getTitleStyle(HSSFWorkbook wb) {
		HSSFCellStyle style = wb.createCellStyle();
		style.setFillForegroundColor(HSSFColor.WHITE.index);
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_NONE);
		style.setBorderRight(HSSFCellStyle.BORDER_NONE);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);

		HSSFFont font = wb.createFont();
		font.setFontHeightInPoints((short) 18);
		font.setFontName("宋体");
		font.setItalic(false);
		font.setStrikeout(false);
		font.setColor(HSSFColor.BLACK.index);
		style.setFont(font);
		return style;
	}

	/**
	 * 设置报表列标题的样式
	 */
	protected HSSFCellStyle getColumnHeaderStyle(HSSFWorkbook wb) {
		HSSFCellStyle style = wb.createCellStyle();
		style.setFillForegroundColor(HSSFColor.WHITE.index);
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);

		HSSFFont font = wb.createFont();
		font.setFontHeightInPoints((short) 12);
		font.setFontName("宋体");
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		font.setItalic(false);
		font.setStrikeout(false);
		font.setColor(HSSFColor.BLACK.index);
		style.setFont(font);
		return style;
	}
}
